<template>
    <div>
        <!-- 面包屑导航区域 -->
        <el-breadcrumb separator-class="el-icon-arrow-right">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>权限管理</el-breadcrumb-item>
            <el-breadcrumb-item>角色管理</el-breadcrumb-item>
        </el-breadcrumb>
        <!-- 角色列表区域 -->
        <el-card>
            <!-- 添加角色按钮区域 -->
            <el-row>
                <el-button type="primary">添加角色</el-button>
            </el-row>
            <!-- 角色列表区域 -->
            <el-table :data="rolesList" border strip>
                <!-- 展开列 -->
                <!-- <el-table-column type="expand" prop="children"> -->
                <el-table-column type="expand">
                    <template slot-scope="scope">
                        <!-- 使用栅格渲染权限分级 -->
                        <!-- el-row一行分为24个列 -->
                        <el-row v-for="(item1,i1) in scope.row.children" :key="item1.id" :class="['bdbottom',i1==0?'bdtop':'']" class="vcenter">    
                            <!-- 渲染一级权限 -->
                            <el-col :span="5">
                                <el-tag closable @close="removeRightById(scope.row,item1.id)">{{item1.authName}}</el-tag>
                                <i class="el-icon-caret-right"></i>
                            </el-col>
                            <!-- 渲染二级和三级权限 -->
                            <el-col :span="19">
                                <!-- 通过for循环 嵌套渲染二级权限 -->
                                <el-row :class="[item2 == 0?'':'bdtop']" :span=9  v-for="(item2) in item1.children" :key="item2.id" class="vcenter">
                                    <el-col :span="6">
                                        <el-tag type="success"  closable @close="removeRightById(scope.row,item2.id)">{{item2.authName}}</el-tag>
                                        <i class="el-icon-caret-right"></i>
                                    </el-col>
                                    <el-col :span="18">
                                        <!--  -->
                                        <el-tag v-for="(item3) in item2.children" :key="item3.id" type="warning" closable @close="removeRightById(scope.row,item3.id)">
                                            {{item3.authName}}
                                        </el-tag>
                                    </el-col>
                                </el-row>
                            </el-col>
                        </el-row>
                        {{scope.row}}
                    </template>
                </el-table-column>
                <!-- 索引列 -->
                <el-table-column type="index"></el-table-column>
                <el-table-column prop="roleName" label="角色名称"></el-table-column>
                <el-table-column prop="roleDesc" label="角色描述"></el-table-column>
                <el-table-column label="操作" width="300px">
                    <template slot-scope="scope" >
                        <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
                        <el-button type="danger" icon="el-icon-delete" size="mini">删除</el-button>
                        <el-button type="warning" icon="el-icon-setting" size="mini" @click="showSetRightDialog(scope.row)">分配权限</el-button>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
        <!-- 分配权限的对话框 -->
        <!-- children:children：实现父子嵌套是用的那一个属性 -->
        <!-- 当我们选中的时候，我们要选中的不是那个文本，而是对应这一项的id值 -->
        <el-dialog :visible.sync="setRightDialogVisible" @closed="setRightsDialogClosed">
                <el-tree
                    :data="rightsList"
                    :props="treeProps"
                    node-key="id"
                    ref="treeRef"
                    default-expand-all
                    :default-checked-keys="defKeys"
                    show-checkbox>
                </el-tree>
            <span slot="footer" class="dialog-footer">
                <el-button @click="setRightDialogVisible=false">取消</el-button>
                <el-button @click="allotRights">确认</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data() {
        return {
            rolesList: [],
            rightsList: [],
            setRightDialogVisible: false,
            treeProps: {
                label: "authName",      //看到的是哪一个属性
                children: "children"    //通过children实现父子间嵌套的
            },
            defKeys: [],                //默认选中节点的id值,
            roleID:'',
        }
    },
    created() {
        this.getRolesList();
    },
    methods: {
        // 获取所有角色的列表
        async getRolesList() {
            const { data: res } = await this.$http.get('roles')
            if(res.meta.status != 200) {
                return this.$message.error(res.meta.msg)
            }
            this.rolesList=res.data;
            console.log(this.rolesList);
        },
        // 根据id删除对应的权限
        async removeRightById(role,right) {
            const confirmResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).catch(error => error)

            if(confirmResult !== 'confirm') {
                return this.$message.info("取消了删除")
            }
            // 'roles/:roleId/rights/:rightId'
            const { data:res } = await this.$http.delete(`roles/${role.id}/rights/${right}`)
            if(res.meta.status !== 200) return this.$message.error("删除权限失败" + res.meta.msg)
            
            // this.getRolesList(); 不建议重新获取数据，因为会把展开的权限信息关闭
            // 因为返回的data是删除权限后的最新数据，可以将返回的数据重新赋值给角色role.给当前的角色信息重新赋值一下权限
            role.children = res.data
            console.log('确认了删除');
        },
        // 显示分配权限的对话框
        async showSetRightDialog(role) {
            this.roleId = role.id
            console.log(111);
            // 获取所有的数据
            const { data: res } = await this.$http.get(`rights/tree`)
            if(res.meta.status !== 200) return this.$message.error("权限数据获取失败！")
            // 把获取到的权限保存到data中
            this.rightsList = res.data;

            // 递归获取三级节点的id
            this.getLeafKeys(role,this.defKeys)
            this.setRightDialogVisible=true
        },
        // 通过递归的方式，获取角色下所有三级权限的id，并保存到数组中
        getLeafKeys(node,arr) {
            // 如果当前node节点不包含children属性，则是三级权限
            if(!node.children){
                return arr.push(node.id)
            }
            // 如果不是三级权限，则使用递归的方式
            node.children.forEach(item => {
                this.getLeafKeys(item,arr)
            })
        },
        // 当关闭权限分配对话框的时候，应该重置 监听分配权限对话框关闭的事件
        setRightsDialogClosed() {
            this.defKeys=[]           
        },
        // 点击为角色分配数据
        async allotRights() {
            // ...展开运算符,将一个数组转化成用逗号分隔的参数序列.
            const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
            
            const idStr = keys.join(',')
            const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`,{ rids: idStr})
            if(res.meta.status !== 200) {
                return this.$message.error("分配权限失败")
            }

            this.$message.success("分配权限成功")
            this.setRightDialogVisible = false;



        },
    }
}
</script>

<style lang="less" scoped>
    .el-tag {
        margin: 7px;
    }
    .bdbottom {
        border-bottom: 1px solid #eee;
    }
    .bdtop {
        border-top: 1px solid #eee
    }
    
</style>